#encoding=utf8
import numpy as np
from PIL import Image
import cPickle as pickle
import scipy.ndimage as spnd
import os.path

def imageSvd(imgPath):
    print "begin read image in '" + imgPath + "' ..."
    #img = spnd.imread(imgPath)
    img = np.array(Image.open(imgPath,"r"))
    R = img[:,:,0]
    G = img[:,:,1]
    B = img[:,:,2]
    print "image shape " + str(R.shape)
    print "\tbeigin svd process ... "

    Ru , Rsigma , Rv = np.linalg.svd(R)
    Gu , Gsigma , Gv = np.linalg.svd(G)
    Bu , Bsigma , Bv = np.linalg.svd(B)
    print "Ru shape"
    print Ru.shape
    print "Rsigma shape"
    print Rsigma.shape
    print "Rv shape"
    print Rv.shape

    print "\tsvd process done "
    return ((R ,Ru , Rsigma , Rv),(G ,Gu , Gsigma , Gv),(B ,Bu , Bsigma , Bv))

def imageBlurring( ((R,Ru , Rsigma , Rv),(G,Gu , Gsigma , Gv),(B,Bu , Bsigma , Bv)) ,clarityPercent=0.6):
    R_new = np.zeros(R.shape)
    G_new = np.zeros(G.shape)
    B_new = np.zeros(B.shape)
    for i in xrange(0,int(clarityPercent*len(Rsigma))):
        R_new += Rsigma[i] * np.dot(Ru[:,i].reshape(-1,1) , Rv[i,:].reshape(1,-1))
    for i in xrange(0,int(clarityPercent*len(Gsigma))):
        G_new += Gsigma[i] * np.dot(Gu[:,i].reshape(-1,1) , Gv[i,:].reshape(1,-1))
    for i in xrange(0,int(clarityPercent*len(Bsigma))):
        B_new += Bsigma[i] * np.dot(Bu[:,i].reshape(-1,1) , Bv[i,:].reshape(1,-1))
    R_new[R_new<0] = 0
    R_new[R_new > 255] = 255
    G_new[G_new<0] = 0
    G_new[G_new > 255] = 255
    B_new[B_new<0] = 0
    B_new[B_new > 255] = 255
    R_new_img = np.rint(R_new).astype("uint8")
    G_new_img = np.rint(G_new).astype("uint8")
    B_new_img = np.rint(B_new).astype("uint8")
    img_new = np.dstack((R_new_img, G_new_img, B_new_img))
    Image.fromarray(img_new).show("clarity percent " + str(clarityPercent))


if __name__ == "__main__":

    fName = "./svdData.pickle"
    if os.path.exists(fName):
        svdDataF = file(fName, "rb")
        svdData = pickle.load(svdDataF)
    else:
        svdData = imageSvd("../dataset/images/img_studio.JPG")
        svdDataF = file(fName, "wb")
        pickle.dump(svdData,svdDataF,True)

    for clarity in np.arange(0.01, 0.1, 0.02):
        print "\tclarity percent "+ str(clarity)
        imageBlurring(svdData,clarity)